package com.silvtar.sync.controller;

import java.net.Socket;
import com.silvtar.io.StdOut;
import com.silvtar.io.StreamToolkit;
import com.silvtar.net.Message;
import com.silvtar.net.NetPack;
import com.silvtar.net.Server;

/**
 * 验证器类
 * 
 * @author silvtar
 * 
 */
public class SSValidator implements Server.Acceptor {
    
    private Server  server;
    private String  ipAddr;
    private int     validatePort;
    private String  validateKey;
    private boolean success   = false;
    private boolean daemonRun = false;

    public void setValidateKey(String validateKey) {
        this.validateKey = validateKey;
    }

    public boolean isSuccess() {
        return success;
    }

    /**
     * 配置验证服务
     * 
     * @param validatePort
     *            服务器的端口号。这个端口号与客户端共用端口号。
     */
    public void configDaemon(int validatePort) {
        this.validatePort = validatePort;

        if (daemonRun) {
            StdOut.printLog("重新配置验证服务...");
            server.close();
            server = new Server(this, this.validatePort);
        } else {
            StdOut.printLog("配置验证服务...");
            server = new Server(this, this.validatePort);
        }

        success = false;
    }

    public void configClient(String ipAddr) {
        this.ipAddr = ipAddr;
        success = false;
    }

    @Override
    public void accept(int identifier) {
        StreamToolkit st = new StreamToolkit(server, identifier);
        Message message = (Message) st.readObject();
        if (message.getType() == Message.VALIDATE && message.getId() == 1) {
            if (message.getContent().equals(validateKey)) {
                st.writeObject(new Message("success", 1, Message.SUCCESS));
            } else {
                st.writeObject(new Message("do not success", 1, Message.SUCCESS));
            }
        }
    }

    public void startValidateDaemon() {
        if (daemonRun) {
            server.listen();
            StdOut.printLog("重新启动验证服务...");
        } else {
            server.listen();
            StdOut.printLog("启动验证服务..");
            daemonRun = true;
        }
    }

    /**
     * 验证两台计算机是否配对
     */
    public boolean validate() {
        Socket socket = NetPack.connect(ipAddr, validatePort);
        StreamToolkit st = new StreamToolkit(socket);
        Message message = new Message(validateKey, 1, Message.VALIDATE);
        st.writeObject(message);
        message = (Message) st.readObject();
        if (message.getType() == Message.SUCCESS && message.getId() == 1) {
            if (message.getContent().equals("success")) {
                success = true;
                StdOut.printLog("验证成功");
            } else {
                success = false;
                StdOut.printLog("验证失败");
            }
        }
        return success;
    }
}
